package com.woniu.finance.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nimbusds.jwt.util.DateUtils;
import com.woniu.finance.entity.Finance;
import com.woniu.finance.entity.RequestParam;
import com.woniu.finance.entity.Tender;
import com.woniu.finance.entity.vo.TendFullVO;
import com.woniu.finance.entity.vo.TenderPlatformAuditVO;
import com.woniu.finance.entity.vo.TenderVO;
import com.woniu.finance.mapper.TenderMapper;
import com.woniu.finance.service.ITenderService;
import com.woniu.platform.entity.PlatformLoan;
import com.woniu.platform.mapper.PlatformLoanMapper;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.data.elasticsearch.annotations.FieldType.Date;

/**
 * <p>
 * 投标表 服务实现类
 * </p>
 *
 * @author o
 * @since 2023-04-25
 */
@Service
public class TenderServiceImpl implements ITenderService {

    @Autowired(required = false)
    private TenderMapper tenderMapper;

    @Override
    public HttpResult<?> saveTender(Tender tender) {
        try {
            tenderMapper.saveTender(tender);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> removeTender(Integer id) {
        try {
            tenderMapper.deleteById(id);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> modifyTender(Tender tender) {
        try {
            tenderMapper.updateById(tender);
            return new HttpResult<>().ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findAllTender() {
        try {
            List<Tender> tenders = tenderMapper.selectList(null);
            return new HttpResult<>().ok(tenders);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findTenderById(Integer id) {
        try {

            Tender tender = tenderMapper.selectById(id);
            return new HttpResult<>().ok(tender);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findTenderByAnnualizedInterestRate1(Double annualizedInterestRate) {
        try {
            List<Tender> tenders = tenderMapper.findTenderByAnnualizedInterestRate1(annualizedInterestRate);
            return new HttpResult<>().ok(tenders);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findTenderByAnnualizedInterestRate2(Double annualizedInterestRate) {
        try {
            List<Tender> tenders = tenderMapper.findTenderByAnnualizedInterestRate2(annualizedInterestRate);
            return new HttpResult<>().ok(tenders);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> findTenderByAnnualizedInterestRate3(Double annualizedInterestRate) {
        try {
            List<Tender> tenders = tenderMapper.findTenderByAnnualizedInterestRate3(annualizedInterestRate);
            return new HttpResult<>().ok(tenders);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult<>().fail();
        }
    }

    @Override
    public HttpResult<?> queryTenderInfoByPage(RequestParam<Tender> param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        QueryWrapper<Tender> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("tender_id");
        queryWrapper.eq("finance_id",param.getData().getFinanceId());
        List<Tender> tenderInfo = tenderMapper.selectList(queryWrapper);
        PageInfo pageInfo = new PageInfo(tenderInfo);
        return new HttpResult<>().ok(pageInfo);
    }

    /**
     * 查询表满状态进行放款
     * @param param
     * @return
     */
    @Override
    public HttpResult queryTendfullByPage(RequestParam<TendFullVO> param) {
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<TendFullVO> tenderList = tenderMapper.queryTendFull(param.getData().getFname(),param.getData().getEname());
        PageInfo pageInfo = new PageInfo(tenderList);
        return new HttpResult<>().ok(pageInfo);
    }

    /**
     * 放款操作
     * @param list
     * @return
     */
    @Autowired
    private PlatformLoanMapper platformLoader;
    @Override
    @Transactional
    public HttpResult insertLoadAndChangeTend(List<TendFullVO> list) {
        //通过Stream流获得标的id
    List<String> ids = list.stream().map(e -> e.getTenderId()).collect(Collectors.toList());
    //批量修改标的状态
    tenderMapper.updateTend(ids);

    PlatformLoan loan = new PlatformLoan();
    List<PlatformLoan> loans = new ArrayList<PlatformLoan>();
        for (TendFullVO t : list) {
            loan.setTenderId(t.getTenderId());
            Date date = new Date();
            SimpleDateFormat dateFormat= new
                    SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            loan.setCreatTime(dateFormat.format(date));
            loan.setFianceMoney(t.getAllFinancingAmount());
            loan.setInterestMoney(t.getRepaymentAmount().subtract(t.getAllFinancingAmount()));
            loans.add(loan);
        }
        for (PlatformLoan l: loans) {
            platformLoader.insert(l);
        }
        return new HttpResult<>().ok();
    }

    @Override
    public HttpResult queryTendPlatformAudit(RequestResult<TenderPlatformAuditVO> param) {
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<TenderPlatformAuditVO> list = tenderMapper.queryTendPlatformAudit(param.getData().getFinanceName(), param.getData().getCoreName());
        PageInfo pageInfo = new PageInfo(list);
        return new HttpResult().ok(pageInfo);

    }

    /**
     * 周期函数
     * 没天凌晨12点修改需要偿还的标的状态
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateTendfull(){
        Date date = new Date();
        SimpleDateFormat dateFormat= new
                SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String nowTime = dateFormat.format(date);
        List<Tender> tendList = tenderMapper.selectList(null);
        for (Tender tender: tendList) {
            if(tender.getFinalRepaymentTime().compareTo(nowTime) < 0){
                tender.setOverdueCompensation(1);
                tenderMapper.insert(tender);
            }
        }
    }

}
